package com.example.community.utils;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


/**
 *
 */
@Component
public class SensitiveFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(SensitiveFilter.class);

    //替换的字符
    private static final String REPLACEMENT = "***";

    private TrieNode rootNode = new TrieNode();//根节点

    //容器在实例化这个bean的时候就会被调用, 即服务启动的时候, 树就已经被初始化了
    @PostConstruct
    public void init(){
        //从类路径中获取一个字节流, 写在try的()里会在运行结束之后自动关掉
        try(
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ){
            String keyword;
            //体会一下这里面是怎么做判断的
            while((keyword = reader.readLine()) != null){
                //添加到前缀树
                this.addKeyword(keyword);
            }
        }catch (IOException e){
            LOGGER.error("加载敏感词文件失败: " + e.getMessage());
        }
    }
    //将一个敏感词添加到前缀树中
    private void addKeyword(String keyword){
        TrieNode tempNode = rootNode;
        for(int i = 0; i < keyword.length(); i++){
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);
            if(subNode == null){
                subNode = new TrieNode();
                tempNode.addSubNode(c, subNode);
            }
            tempNode = subNode;
            if(i == keyword.length() - 1){
                tempNode.setKeywordEnd(true);
            }
        }
    }

    /**
     * 过滤敏感词
     * @param text 待过滤的文本
     * @return 过滤后的结果
     */
    public String filter(String text){
        if(StringUtils.isBlank(text)){
            return null;
        }
        //指针1
        TrieNode tempNode = rootNode;
        int begin = 0;
        int position = 0;
        //结果
        StringBuilder sb = new StringBuilder();
        while(position < text.length()){
            char c = text.charAt(position);
            //跳过符号
            if(isSymbol(c)){
                if(tempNode == rootNode){
                    sb.append(c);
                    begin++;
                }
                position++;//无论符号在开头还是中间, 指针position都往后移
                continue;
            }
            //检查下一级节点
            tempNode = tempNode.getSubNode(c);
            if(tempNode == null){
                //以当前begin开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                position = ++begin;
                tempNode = rootNode;
            }else if(tempNode.isKeywordEnd()){
                //找到敏感词了, 替换掉这一段字符串
                sb.append(REPLACEMENT);
                begin = ++position;
                tempNode = rootNode;
            }else{
                //检查下一个字符
                position++;
            }
        }
        //将最后一批字符计入结果
        sb.append(text.substring(begin));
        return sb.toString();
    }
    //判断是否为符号
    private boolean isSymbol(Character c){
        //不是字母表符号, 也不在东亚文字范围内
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    //节点内部类, 节点中有该点对应字符是否为敏感词, 以及该点的子节点 char-TrieNode 键值对表
    private class TrieNode{
        //每一个节点有一个关键词结束标识, 是否为敏感词
        private boolean isKeywordEnd = false;
        //子节点(key是下一个字符, value为子节点)
        private Map<Character, TrieNode>  subNodes = new HashMap<>();

        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        public void addSubNode(Character c, TrieNode node){
            subNodes.put(c, node);
        }
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }
    }
}
